/*
    Author:xfz
    Desc:对调试打印进行一层抽象，方便后续使用操作
*/
#include "def.h"
#include "usart.h"
#include <stdio.h>
#define USART1_RDR_Address 0x40013824
#define USART1_TDR_Address 0x40013828
DMA_InitTypeDef DMA_InitStructure;
uint8_t usart1_rxBuf[USART1_DMA_BUF_SIZE + 10];
Type_OnDataReceived OnDataReceived = NULL;

/*用于标准库的设置文件*/
/**
 * @brief  Retargets the C library printf function to the USART.
 * @param  None
 * @retval None
 */
int fputc(int ch, FILE *f)
{
    /* Place your implementation of fputc here */
    /* e.g. write a character to the USART */
    USART_SendData(USART1, (uint8_t)ch);

    /* Loop until transmit data register is empty */
    while (USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET)
    {
    }
    return ch;
}
int fgetc(FILE *f)
{
    while (USART_GetFlagStatus(USART1, USART_FLAG_RXNE) == RESET)
    {
    }
    return (int)USART_ReceiveData(USART1);
}

GBool usart_isRxBufNotEmpty(void)
{
    return USART_GetFlagStatus(USART1, USART_FLAG_RXNE);
}
GBool usart_rxBufferTimeout(void)
{
    uint32_t scantimeout = 0;
    fflush(stdin);
    while (USART_GetFlagStatus(USART1, USART_FLAG_RXNE) == RESET)
    {
        scantimeout++;
        if (scantimeout >= SCANF_TIMEOUT)
        {
            break;
        }
    }
    if (scantimeout < SCANF_TIMEOUT)
    {
        return GFalse;
    }
    else
    {
        return GTrue;
    }
}
void usart_write(unsigned char *buffer, unsigned int counter)
{
    unsigned int tmp = 0;
    for (tmp = 0; tmp < counter; tmp++)
    {
        USART_SendData(USART1, (uint8_t)buffer[tmp]);
        while (USART_GetFlagStatus(USART1, USART_FLAG_TXE) == RESET)
        {
        }
    }
}

void usart_rxReset(void)
{
    uint32_t scantimeout = 0;
    while (GTrue)
    {
        while (USART_GetFlagStatus(USART1, USART_FLAG_RXNE) == RESET)
        {
            scantimeout++;
            if (scantimeout >= (SCANF_TIMEOUT / 10))
            {
                return;
            }
        }
        USART_ReceiveData(USART1);
    }
}
//串口发送接收初始化
//发送没有使用dma，接收使用了，接收使用了DMA并且同时启用了满、半满和空闲中断
void usart_init(void)
{
    NVIC_InitTypeDef NVIC_InitStructure;
    USART_InitTypeDef usart_InitTypeDef;
    GPIO_InitTypeDef Gpio_InitStructure;

    RCC_APB2PeriphClockCmd(RCC_APB2Periph_SYSCFG, ENABLE);
    /*--------------------------中断配置------------------------------*/
    NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelPriority = 0;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStructure);
    NVIC_InitStructure.NVIC_IRQChannel = DMA1_Ch2_3_DMA2_Ch1_2_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelPriority = 0;
    NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
    NVIC_Init(&NVIC_InitStructure);
    /*--------------------------基础外设配置--------------------------*/
    // PB6 TX PB7 RX

    // 打开GPIOB外设使能
    RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOB, ENABLE);
    //打开USART1 外设使能
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
    // PIN 6和PIN 7设为外设功能
    GPIO_PinAFConfig(GPIOB, GPIO_PinSource6, GPIO_AF_0); // TX
    GPIO_PinAFConfig(GPIOB, GPIO_PinSource7, GPIO_AF_0); // RX
    //初始化GPIO设置
    //初始化PIN6
    Gpio_InitStructure.GPIO_Pin = GPIO_Pin_6;
    Gpio_InitStructure.GPIO_Mode = GPIO_Mode_AF;
    Gpio_InitStructure.GPIO_Speed = GPIO_Speed_10MHz;
    Gpio_InitStructure.GPIO_OType = GPIO_OType_PP;
    Gpio_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
    GPIO_Init(GPIOB, &Gpio_InitStructure);
    //初始化pin7
    Gpio_InitStructure.GPIO_Pin = GPIO_Pin_7;
    GPIO_Init(GPIOB, &Gpio_InitStructure);
    //初始化串口配置
    usart_InitTypeDef.USART_BaudRate = BAUD;
    usart_InitTypeDef.USART_WordLength = USART_WordLength_8b;
    usart_InitTypeDef.USART_StopBits = USART_StopBits_1;
    usart_InitTypeDef.USART_Parity = USART_Parity_No;
    usart_InitTypeDef.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
    usart_InitTypeDef.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
    USART_Init(USART1, &usart_InitTypeDef);

    usart_rxReset(); //丢掉缓存
    USART_ITConfig(USART1, USART_IT_IDLE, ENABLE);
    /*-----------------------DMA配置-------------------------*/
    /*DMA基础配置*/
    RCC_AHBPeriphClockCmd(RCC_AHBPeriph_DMA1, ENABLE);
    DMA_InitStructure.DMA_BufferSize = USART1_DMA_BUF_SIZE;
    DMA_InitStructure.DMA_PeripheralDataSize = DMA_PeripheralDataSize_Byte;
    DMA_InitStructure.DMA_MemoryDataSize = DMA_MemoryDataSize_Byte;
    DMA_InitStructure.DMA_PeripheralInc = DMA_PeripheralInc_Disable;
    DMA_InitStructure.DMA_MemoryInc = DMA_MemoryInc_Enable;
    DMA_InitStructure.DMA_Mode = DMA_Mode_Circular;
    DMA_InitStructure.DMA_M2M = DMA_M2M_Disable;

    /*DMA串口接收配置*/
    DMA_InitStructure.DMA_MemoryBaseAddr = (uint32_t)usart1_rxBuf;
    DMA_InitStructure.DMA_DIR = DMA_DIR_PeripheralSRC;
    DMA_InitStructure.DMA_Priority = DMA_Priority_Medium;
    DMA_InitStructure.DMA_PeripheralBaseAddr = USART1_RDR_Address;
    DMA_Init(DMA1_Channel3, &DMA_InitStructure);
    USART_DMACmd(USART1, USART_DMAReq_Rx, ENABLE);
    DMA_ITConfig(DMA1_Channel3, DMA_IT_TC | DMA_IT_HT | DMA_IT_TE, ENABLE);
    DMA_ClearFlag(DMA1_IT_TC3);
    DMA_ClearFlag(DMA1_IT_HT3);
    DMA_ClearFlag(DMA1_IT_TE3);
    USART_ClearITPendingBit(USART1, USART_IT_IDLE);
    USART_ClearFlag(USART1, USART_FLAG_IDLE);
    USART_Cmd(USART1, ENABLE);
    DMA_Cmd(DMA1_Channel3, ENABLE);
}
void usart_deinit(void)
{
    USART_Cmd(USART1, DISABLE);
    DMA_Cmd(DMA1_Channel3, DISABLE);

    DMA_ClearFlag(DMA1_IT_TC3);
    DMA_ClearFlag(DMA1_IT_HT3);
    DMA_ClearFlag(DMA1_IT_TE3);
    DMA_ITConfig(DMA1_Channel3, DMA_IT_TC | DMA_IT_HT | DMA_IT_TE, DISABLE);
    DMA_DeInit(DMA1_Channel3);
    USART_ClearITPendingBit(USART1, USART_IT_IDLE);
    USART_ClearFlag(USART1, USART_FLAG_IDLE);
    USART_DMACmd(USART1, USART_DMAReq_Rx, DISABLE);
    USART_ITConfig(USART1, USART_IT_RXNE, DISABLE);
    USART_DeInit(USART1);
    GPIO_DeInit(GPIOB);
}

void usart_dma_reset(void)
{
    DMA_Cmd(DMA1_Channel3, DISABLE);
    DMA_Init(DMA1_Channel3, &DMA_InitStructure);
    DMA_Cmd(DMA1_Channel3, ENABLE);
}

unsigned int middleCounter = 0;
void usart_idel_handler(void)
{

    uint8_t clar = clar;
    unsigned char *dataBufferP = NULL;
    unsigned int procedLen = 0;
    //接收到的数据长度为 总长度-剩余空闲的buff长度-上次的位置(middleCounter)
    //接收的地址即为上次的位置
    if (USART_GetITStatus(USART1, USART_IT_IDLE) != RESET)
    {
        USART_ClearITPendingBit(USART1, USART_IT_IDLE);
        procedLen = USART1_DMA_BUF_SIZE - DMA_GetCurrDataCounter(DMA1_Channel3) - middleCounter;
        dataBufferP = (unsigned char *)&usart1_rxBuf[middleCounter];
        if (OnDataReceived != NULL)
        {
            // printf("I\n");
            OnDataReceived(dataBufferP, procedLen);
        }
        middleCounter = 0;
        usart_dma_reset();
    }
    //此时数据可剩余数据，这里采用回调的形式进行操作，避免产生恶心的代码
}

void usart_dma_handler(void)
{
    unsigned char *dataBufferP = NULL;
    unsigned int procedLen = 0;
    if (DMA_GetITStatus(DMA1_IT_TC3) != RESET)
    {

        // DMA全满
        procedLen = USART1_DMA_BUF_SIZE - middleCounter;
        middleCounter = 0;
        dataBufferP = (unsigned char *)&usart1_rxBuf[middleCounter];
        if (OnDataReceived != NULL)
        {
            // printf("F\n");
            OnDataReceived(dataBufferP, procedLen);
        }

        DMA_ClearITPendingBit(DMA1_IT_TC3);
        // usart_dma_reset();
    }
    if (DMA_GetITStatus(DMA1_IT_HT3) != RESET)
    {
        //半满
        // DMA全满

        middleCounter = USART1_DMA_BUF_SIZE - DMA_GetCurrDataCounter(DMA1_Channel3);
        dataBufferP = (unsigned char *)usart1_rxBuf;
        if (OnDataReceived != NULL)
        {
            // printf("HALF\n");
            OnDataReceived(dataBufferP, middleCounter);
        }
        DMA_ClearITPendingBit(DMA1_IT_HT3);
    }
    if (DMA_GetITStatus(DMA1_IT_TE3) != RESET)
    {
        DMA_ClearITPendingBit(DMA1_IT_TE3);
        //错误
    }
}
